<template>
  <div class="app-container">
      <div class="filter-container">
         <el-input v-model="SearchForm.RoleName" style="width:200px" placeholder="角色名称" class="filter-item"></el-input>
         <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
         <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleAdd">添加</el-button>
      </div>
          <el-table
            :data="DataList"
            border
            fit
            highlight-current-row
            v-loading="listLoading"
            style="width: 100%">
            <el-table-column
              prop="RoleName"
              label="角色名称"
              align="center"
              width="180">
            </el-table-column>
            <el-table-column
              prop="RoleStatus"
              label="角色状态"
              align="center"
              :formatter="formatterRoleStatus"
              width="180">
            </el-table-column>
            <el-table-column
              prop="CreateTimeStr"
               align="center"
              label="创建时间">
            </el-table-column>
             <el-table-column
                align="center"
             width="350"
              label="操作">
                 <template slot-scope="scope">
                   <el-button type="warning" size="mini" @click="handleShowSetMoudle(scope.row)">分配权限菜单</el-button>
                  <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                  <el-button  size="mini" type="success" @click="handleModifyStatus(scope.row)">{{scope.row.RoleStatus==1?'禁用':'启用'}} 
                  </el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.row)"> 删除</el-button>
                </template>
            </el-table-column>
          </el-table>
           <pagination v-show="TotalCount>0" :total="TotalCount" :page.sync="SearchForm.pageIndex" :limit.sync="SearchForm.pageSize" @pagination="getList" />

          <!-- 编辑新增弹出框 -->
          <el-dialog
              :title="form.ID==0?'新增角色':'编辑角色'"
              :visible.sync="AddOrEditdialogVisible"
              width="30%"
              @close="handleClose"
             >
              <div>
                <el-form ref="form" :model="form" :rules="rule" label-width="80px">
                  <el-form-item label="角色名称" prop="RoleName">
                    <el-input v-model="form.RoleName"></el-input>
                  </el-form-item>
                </el-form>
              </div>
              <span slot="footer" class="dialog-footer">
                <el-button @click="AddOrEditdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">确 定</el-button>
              </span>
          </el-dialog>

          <!-- 设置角色权限菜单 -->
          <el-dialog
           :title="'设置角色权限菜单'"
           :visible.sync="IsTreedialogVisible"
            width="50%"
          >
              <div>
                  <tree-table :data="dataTree"  :columns="columns"   :expand-all="expandAll" border>
                  </tree-table>
              </div>
              <span slot="footer" class="dialog-footer">
                <el-button @click="IsTreedialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSetMoudle">确 定</el-button>
              </span>
          </el-dialog>
  </div>
</template>

<script>
Array.prototype.clone=function(){ 
    return [].concat(this); 
    //或者 return this.concat();
}
import req from '@/utils/req'
import Pagination from '@/components/Pagination' 
import treeTable from '@/components/TreeTable'
import treeToArray from './customEval'
export default {
   components: { Pagination,treeTable },
  data() {
   
    return {
        SearchForm:{
          RoleName:'',
          pageIndex:1,
          pageSize:10,
        },
        form:{
          ID:0,
          RoleName:''
        },
        TotalCount:0,
        DataList:[],
        AddOrEditdialogVisible:false,//
        listLoading:false,
        //验证
        rule:{
          RoleName:[
             { required: true, message: '请输入角色名称', trigger: 'blur' },
          ]
        },
       //设置权限菜单的字段
      func: treeToArray,
      expandAll: false,
      IsTreedialogVisible:false,
      dataTree:[],
      RoleID:0,//设置的角色ID
      columns: [
        {
          text: '菜单名称',
          value: 'MName',
          width: 200
        },
        {
          text: '菜单编码',
          value: 'MCode'
        }
      ],
    }
  },
  watch: {
  
  },
  created() {
    this.getList();
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  },
  methods: {
    handleFilter(){
      this.SearchForm.pageIndex=1;
      this.getList();
    },
   formatterRoleStatus(row, column, cellValue, index){
      return cellValue==1?'启用 ':'禁用'
    },
   getList(){
     this.listLoading = true
     req.get('sys/Role/pagelist',this.SearchForm).then(res=>{
       this.DataList=res.Data.roleList;
       this.TotalCount=res.Data.TotalCount
         setTimeout(() => {
          this.listLoading = false
        }, 500)
     });
   },
   //新增
   handleAdd(){
     this.AddOrEditdialogVisible=true;
   },
   handleUpdate(row){
     this.form=Object.assign({}, row) // copy obj;
     this.AddOrEditdialogVisible=true;

   },
   //关闭的回调
   handleClose(done){
     this.form.ID=0;
     this.form.RoleName=''
   },
   handleSubmit(){
     var url=this.form.ID==0?'sys/Role/Add':'sys/Role/Edit';
         this.$refs['form'].validate((valid) => {
           if(valid){
            req.post(url,this.form).then(res=>{
                  if(res.StatusCode===200){
                      this.$notify.success({ title: '成功',message:'操作成功' });
                      this.AddOrEditdialogVisible=false;
                      this.getList();
                  }
                });
           }
       })
   },
   //禁用启用
   handleModifyStatus(row){
      let str=row.RoleStatus==1?'禁用':'启用'
      this.$confirm(`此操作将${str}该角色 , 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
                 row.RoleStatus=row.RoleStatus==1?2:1
                req.post('sys/Role/Edit',row).then(res=>{
                  if(res.StatusCode===200){
                      this.$notify.success({ title: '成功',message:  str+'成功'});
                      this.getList();
                  }
                });

        }).catch(() => {
        });
   },
   //删除
   handleDelete(row){
       this.$confirm(`此操作将永久删除该角色 , 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
                req.post('sys/Role/Delete',row).then(res=>{
                  if(res.StatusCode===200){
                      this.$notify.success({ title: '成功',message:  '删除成功'});
                      this.getList();
                  }
                });
        }).catch(() => {
        });
   },
   //-----设置权限菜单 -----
   handleShowSetMoudle(row){
     this.RoleID=row.ID;
     req.post('sys/role/GetMoudleByRole',row).then(res=>{
      this.dataTree=res.Data;
      this.IsTreedialogVisible=true;
     });
   },
   handleSetMoudle(){
      var ResList=[];
      var allMoudle=this.dataTree.clone()
      this.FilterMoudle(allMoudle,ResList)
      let data={RoleID:this.RoleID,SysModules:ResList};
      req.post('sys/role/SetMoudle',data).then(res=>{
        if(res.StatusCode===200){
          this.$notify.success({ title: '成功',message:  '设置成功'});
            this.getList();
            this.IsTreedialogVisible=false;
        }
     });
   },
  //过滤树形菜单
   FilterMoudle(moudles,ResList){
     for (let index = 0; index < moudles.length; index++) {
       const el = moudles[index];
         if(el.checks){
           if(el.Childrens){
            this.FilterMoudle(el.Childrens,ResList);
           }
            ResList.push({ID:el.ID ,MCode:el.MCode,MName:el.MName});
            continue;
          }
            if (el.Childrens)
                {
                    if(this.IsIscheckChild(el.Childrens))
                    {
                      this.FilterMoudle(el.Childrens, ResList);
                      ResList.push({ID:el.ID ,MCode:el.MCode,MName:el.MName});
                    }
            }
     }
   },
   //判断下级菜单是否有选中
   IsIscheckChild(moudles){
        for (let index = 0; index < moudles.length; index++) {
          const el = moudles[index];
          if(el.checks)
             return true;
          if(el.Childrens){
            return this.IsIscheckChild(el.Childrens)
          }
        }
        return false;
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
 
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
